#! /usr/bin/env Rscript --vanilla --default-packages=utils,stats

suppressPackageStartupMessages(library("optparse"))

# Usage
option_list = list(
    make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default]"),
    make_option(c("-i", "--tslist"), metavar="FILENAME", help="File with list of functional image file names (i.e. 4D time-series)"),
    make_option(c("-o", "--corlist"), metavar="FILENAME", help="File with list of prefix output correlation matrix file names"),
    make_option(c("-m", "--mask"), metavar="FILENAME", help="Brain mask to restrict computation of all possible correlations in the brain")
)

# Read in stuff from command-line
optparse = OptionParser(option_list=option_list)
opt = parse_args(optparse)

# Check required input args
if (is.null(opt$tslist) || is.null(opt$corlist) || is.null(opt$mask)) {
    print_help(optparse)
    q("no", 1)
}

# Check input args
if (!file.exists(opt$tslist))
    stop("Could not find file '", opt$tslist, "' with list of input functional filenames")
if (!file.exists(opt$corlist))
    stop("Could not find file '", opt$corlist, "' with list of output  correlation prefix filenames")
if (!file.exists(opt$mask))
    stop("Could not find brain mask:", opt$mask)

# Read in list of input filenames
ts.files = as.character(read.table(opt$tslist, header=F)[,1])

# Read in list of output prefix filenames
cor.files = as.character(read.table(opt$corlist, header=F)[,1])

# Run cors
setwd("..")
source("connectivity.R")

tmp = ni.cor.subs(ts.files, cor.files, opt$mask, verbose=opt$verbose)

setwd("script")

q("no", 0)
